package com.zhb.cloud.encrypt.advice;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhb.cloud.anno.Encrypt;
import com.zhb.cloud.exception.ServiceException;
import com.zhb.cloud.utils.AESEncryptUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: EncryptResponseBodyAdvice
 * @Description:请求响应处理类 对加了@Encrypt的方法的数据进行加密操作
 * @author: zhb1316783262@163.com
 * @date: 2019年3月6日下午2:54:19
 */
@ControllerAdvice
@Slf4j
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

	private ObjectMapper objectMapper = new ObjectMapper();
	@Value("${encrypt.key}")
	private String key;

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
//		// 可以通过调用EncryptResponseBodyAdvice.setEncryptStatus(false);来动态设置不加密操作
//		Boolean status = encryptLocal.get();
//		if (status != null && status == false) {
//			encryptLocal.remove();
//			return body;
//		}
		long startTime = System.currentTimeMillis();
		boolean encrypt = false;
		if (returnType.getMethod().isAnnotationPresent(Encrypt.class)) {
			encrypt = true;
		}
		if (encrypt) {
			try {
				String content = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
				if (!StringUtils.hasText(key)) {
					throw new ServiceException("未配置密钥");
				}
				String result = AESEncryptUtil.encrypt(content, key);
				long endTime = System.currentTimeMillis();
				log.debug("Encrypt Time:[{}] ms", (endTime - startTime));
				return result;
			} catch (Exception e) {
				log.error("加密数据异常", e);
			}
		}
		return body;
	}

}
